package com.gnerv.battle.boot.framework.core.tools;


import com.gnerv.battle.boot.framework.core.exception.BusinessException;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Gnerv LiGen
 */
public class ExecTools {

    private ExecTools() {
    }

    public static String exec(String command) {
        return exec(command, null);
    }

    public static String exec(String command, File workingDir) {
        try {
            Process process = Runtime.getRuntime().exec(command, null, workingDir);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            // 阻塞当前线程，并等待外部程序中止后获取结果码
            process.waitFor();
            return result.toString();
        } catch (IOException | InterruptedException e) {
            throw new BusinessException("start soft error", e);
        }
    }

}
